<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/3/4
 * Time: 11:16
 */
class settlement{
    public function index(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorModel= M("mivendor");
        $agentModel = M("vendor_agent");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $condition['openid']=$userName;
        $userResult = $customerUser->where($condition)->find();
        if($userResult){
            //不需要登陆
            $result['isbind']=true;
            $result['agent']=$userResult['agent'];
            switch($userResult['agent']){
                case 'vendor':
                    $vendorInfo =$vendorModel->where("fromCustomerUserId=".$userResult['id'])->find();
                    $result = array_merge($result,$vendorInfo);
                    break;
                case 'vendoragent':
                    $agentInfo =$agentModel->where("fromCustomerUserId=".$userResult['id'])->find();
                    $result = array_merge($result,$agentInfo);
                    break;
            }
        }else{
            $result['isbind']=false;
        }
        Output::instance()->module("settlement",'index')->object($result);

    }
    public function login($loginName,$password){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $userName=Session::$user['userName'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        $vendorModel= M("mivendor");
        $agentModel = M("vendor_agent");
        Session::switchCustomer($customerId);
        $password = Encryption::password($password);
        $condition['a.loginName']=array('eq',$loginName);
        $condition['a.password']=array('eq',$password);
        $result = $customerUser->alias("a")
            ->where($condition)
            ->field("a.agent,a.id as customerUserId,a.openid")
            ->find();
        switch($result['agent']){
            case 'vendor':
                $vendorInfo =$vendorModel->where("fromCustomerUserId=".$result['customerUserId'])->find();
                $result = array_merge($result,$vendorInfo);
                break;
            case 'vendoragent':
                $agentInfo =$agentModel->where("fromCustomerUserId=".$result['customerUserId'])->find();
                $result = array_merge($result,$agentInfo);
                break;
        }
        if(!$result||($result['agent']!='vendor'&&$result['agent']!='vendoragent')){
            Output::instance()->resultCode(1,"账号或密码不正确!");
            return;
        }else{
            if($result['openid']!=$userName){
                $customerUser->where("id=".$result['customerUserId'])->setField("openid",$userName);
            }
            unset($result['openid']);
            $result['isbind']=true;
            Output::instance()->object($result);
        }

    }
    public function accountList($id,$agent,$type=0,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        if($type){
            $vendorAccount = M("account_vendor");
            $agentAccount = M("account_agent");
        }else{
            $vendorAccount = M("vendor_tixian");
            $agentAccount = M("agent_tixian");
        }
        Session::switchCustomer($customerId);
        switch($agent){
            case 'vendor':
                if($type) {
                    $accountList = $vendorAccount->where("vId=$id and status=0")->limit($start, $limit)->order('createTime desc')->select();
                }else{
                    $accountList = $vendorAccount->where("vId=$id and state=0")->limit($start, $limit)->order('createTime desc')->select();
                }
                break;
            case 'vendoragent':
                $accountList =$agentAccount->where("agentId=$id")->limit($start,$limit)->order('createTime desc')->select();
                break;
            default:
                $accountList=null;
                break;
        }
        Output::instance()->object($accountList);
    }
    public function saveCash($id,$cash,$agent,$cuid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
//        if(date("N")!=2){
//            Output::instance()->resultCode(1,'每周二才可以申请结算！');
//            return;
//        }
        if(!preg_match('/^[0-9]{1,}\.?\d{1,}$|^\d$/',$cash)){
            Output::instance()->resultCode(1,'请输入数字！');
            return;
        }
        if($cash<100){
            Output::instance()->resultCode(1,'单笔结算金额必须大于100元！');
            return;
        }
        Session::switchCustomer(0);
        $tixianModel = M("");
        $user_role_model = M('customer_user_role');
        $role_model = M('role');
        Session::switchCustomer($customerId);
        $TemplateModel = M("template_messages");
        $customerUser = M("customer_user");
        //孟慧添加于20180309用于结算时间限定
        $mivendor = M("mivendor");
        //获取商家的结算时间类型以及结算时间设置
        $vendorInfo = $mivendor->field('settlementTimeType,settlementTimeSetting')->where("id=$id")->find();
        //结算时间设置为周几到周几的情况
        if ($vendorInfo['settlementTimeType'] == 'week'){
            $settingInfo = explode(',',$vendorInfo['settlementTimeSetting']);
            $firstInfo = $settingInfo[0];
            $secondInfo = $settingInfo[1];

            if((date("N")>$secondInfo) || (date("N")< $firstInfo) ){
                Output::instance()->resultCode(1,'每周'. $firstInfo.'到周'.$secondInfo.'才可以申请结算！');
                return;
            }
        }else if ($vendorInfo['settlementTimeType'] == 'month') {
            //结算时间设置为每月几号到几号的情况
            $settingInfo = explode(',',$vendorInfo['settlementTimeSetting']);
            $firstInfo = $settingInfo[0];
            $secondInfo = $settingInfo[1];

            if((date("d")>$secondInfo) || (date("d")< $firstInfo)){
                Output::instance()->resultCode(1,'每月自'. $firstInfo.'日到'.$secondInfo.'日才可以申请结算！');
                return;
              }
        }
        //修改到此处上面位置
        $millisecond = explode(' ', microtime());
        $tixianNumber = date('YmdHis').sprintf('%.0f',$millisecond[0]*1000).mt_rand(100,999);
        $data['cash']=$cash;
        $data['state']=0;
        $data['tixianNumber']=$tixianNumber;
        $data['createTime']=date('Y-m-d H:i:s');
        switch($agent){
            case 'vendor':
//                $userInfo = $tixianModel->table('wx_mivendor')->alias('a')
//                    ->join('inner join wx_customer_user b on a.fromCustomerUserId=b.id')
//                    ->where("a.id=$id")
//                    ->field('b.openid,balance')
//                    ->find();
                $userInfo['balance'] = $tixianModel->table('wx_mivendor')->where("id=$id")->getField('balance');
                $userInfo['openid'] = $customerUser->where("id=$cuid")->getField('openid');
                if($userInfo['balance']<$cash){
                    Output::instance()->resultCode(1,'余额不足！');
                    return;
                }
                $data['vId']=$id;
                $tixianModel->table("wx_vendor_tixian")->add($data);
                $sql = "update wx_mivendor set balance=balance-$cash,totalTixian=totalTixian+$cash where id = $id";

                break;
            case 'vendoragent':
//                $userInfo = $tixianModel->table('wx_vendor_agent')->alias('a')
//                    ->join('inner join wx_customer_user b on a.fromCustomerUserId=b.id')
//                    ->where("a.id=$id")
//                    ->field('b.openid,balance')
//                    ->find();
                $userInfo['balance'] = $tixianModel->table('wx_vendor_agent')->where("id=$id")->getField('balance');
                $userInfo['openid'] = $customerUser->where("id=$cuid")->getField('openid');
                if($userInfo['balance']<$cash){
                    Output::instance()->resultCode(1,'余额不足！');
                    return;
                }
                $data['agentId']=$id;
                $tixianModel->table("wx_agent_tixian")->add($data);
                $sql = "update wx_vendor_agent set balance=balance-$cash,totalTixian=totalTixian+$cash where id = $id";

                break;
        }
        $result = $tixianModel->query($sql);
        if($result!==false){
            //发送模板消息和站内消息
            $toUser = $userInfo['openid'];
            if($toUser){
                $twhere['status'] = "payment";
                $templatemsg = $TemplateModel->where($twhere)->find();
                $templateId = $templatemsg['templateId'];
                $data['first'] = array('value'=> '亲，您有一个结算单已经成功提交。','color'=>"#743A3A");
                $data['keyword1'] = array('value'=> $tixianNumber,'color'=>'#173177');
                $data['keyword2'] = array('value'=> date("Y-m-d H:i:s",time())."\n金额：".$cash,'color'=>'#173177');
                $data['remark'] = array('value'=> '请等待审核，3个工作日内审核完成。',"color"=>'#008000');
                $url = C("SERVER_HOST") . "call.html?customerId=" . $customerId ."&module=settlement&method=index";

                $template_id = $templateId;
                $url = urlencode($url);
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
            }
            //                $roleId = $role_model->where(['cid' => $customerId, 'englishRole' => 'newSettlementAdmin'])->getField('id');
//                $receiveIds = $user_role_model->alias('r')
//                    ->join('wx_customer_user u on u.id = r.userId')
//                    ->where(['r.cid' => $customerId, 'r.roleId' => $roleId, 'u.vid' => ['exp', 'is null']])
//                    ->getField('r.userId', true);//接收人id集合数组
//                $receiveIds = array_unique($receiveIds);
            $receiveIds = $customerUser->where(['customerId' => $customerId, 'agent' => 'business'])->getField('id', true);
            $message = '<p>您收到一条结算单号为' . $tixianNumber . '的结算申请，请前往结算中心查看，<a href = "#/joymap/incomeAndSettlement/settlement">前往查看</a></p>';
            PlatMessageAction::pushMessage('申请结算提醒', $message, $receiveIds, '', 0, 'newAllocation', '结算', 2, 1, 0, 0, $message, $customerId);
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
}